#!/usr/bin/env ruby

require 'digest/md5'

class GradleWrapper
	@global_url
	@dest_root

	@sourcr_path
	@name_without_ext
	@basename
	@version
	@hashdir
	@source_url

	attr_accessor :dryrun

	def initialize(path)
		@dest_root = "$HOME/.gradle/wrapper/dists"
		@global_url = "https://services.gradle.org/distributions"

		if path  == 'cleanall'
		elsif path == 'ls'
		else
			@source_path = path
			@basename = File.basename @source_path
			@name_without_ext = self.nameWithoutExt(@basename)
			@version = getVersion @source_path
			@source_url = "#{@global_url}/#{@basename}"
			if @version > 1.6
				@hashdir = hashNewer @source_url
			else
				@hashdir = hashOlder @source_url
			end
			puts "ref url: #{@source_url}"
		end
	end

	def checkFolders
		dest_path = "#{@dest_root}/#{@name_without_ext}/#{@hashdir}/#{@basename}"
		puts "check folders:"
		system "ls #{dest_path}"
		system "ls #{@dest_root}/"
	end

	def install

		dest_path = "#{@dest_root}/#{@name_without_ext}/#{@hashdir}/#{@basename}"

		dest_dir = "#{@dest_root}/#{@name_without_ext}/#{@hashdir}"
		system "mkdir -p #{dest_dir}"

		puts "link #{@source_path} to #{dest_path}"
		linkFileToWrapper(@source_path, dest_path) if not self.dryrun
	end

	def getVersion(path)
		ver_regex = /\d+\.\d+\.*\d*/
		path=~ver_regex
		version = $&.to_f
		puts "ver : #{version}"
		return version
	end

	def nameWithoutExt(fname)
		reg = /(.zip)/
		off = fname=~reg
		name=fname[0, off]
	end

	def hashNewer(str)
		md5v = Digest::MD5.hexdigest(str)
		num = md5v.to_i(16)
		hashv = num.to_s(36)
	end

	def hashOlder(str)
		md5v = Digest::MD5.hexdigest(str)
		num = md5v.to_i(16)
		hashv = num.to_s(32)
	end

	def linkFileToWrapper(source, dest)
		puts "linking..."
		# cmd = "ln -fs #{source} #{dest}"
		cmd = "cp -rf #{source} #{dest}"
		puts cmd
		system cmd
	end

	def clean
		dest_path = "#{@dest_root}/#{@name_without_ext}/#{@hashdir}/#{@basename}"
		cmd = "rm -rf #{dest_path}"
		puts cmd
		system cmd
	end

	def cleanall
		dest_path = "#{@dest_root}"
		cmd = "rm -rf #{@dest_root}/*"
		puts cmd
		system cmd
	end

	def ls
		cmd = "ls -ls #{@dest_root}/"
		puts cmd
		system cmd
	end
end

# ======================================= CMD 

command = fullpath = $*[0]

# system "ls $HOME/.gradle/wrapper/dists"

if not fullpath
	puts "Please input gradle local file path."
	puts "Examples:"
	puts "ruby gradlewrapper.rb dryrun $HOME/gradle-4.4.1-all.zip"
	puts "ruby gradlewrapper.rb $HOME/gradle-4.4.1-all.zip"
	puts "ruby gradlewrapper.rb cleanall"
	puts "ruby gradlewrapper.rb ls"

else
	if command == 'dryrun'
		fullpath = $*[1]
	end
	
	g = GradleWrapper.new fullpath
	g.dryrun = true if command == 'dryrun'

	puts fullpath

	case fullpath
	when "cleanall"
		g.cleanall
	when "ls"
		g.ls
	when "dryrun"
		g.dryrun = true
		puts "#{g.dryrun}" if g.dryrun
	else
		g.install
		g.checkFolders
	end
end